package com.vegetable.modules.service.baseData.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class QiniuServiceImpl {

    @Autowired
    private UploadManager uploadManager;
    @Autowired
    private String domain;
    @Autowired
    private Auth auth;
    private static final String bucket = "ds-crm";

    private static final String prefix = "http://cdn.deshuo.online/";


    public String upload(MultipartFile file, String subFolder) throws IOException {
        String originalFilename = file.getOriginalFilename();
        // 生成新的文件名（防止重复）
        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        // 上传到七牛云
        String url = upload(file.getBytes(), fileName, subFolder);
        log.info("上传图片地址：{}", url);
        return prefix + url;
    }

    public String upload(byte[] fileBytes, String fileName, String subFolder) throws QiniuException {
        // 1. 生成当天日期文件夹路径 (格式: yyyyMMdd)
        String dateFolder = generateDateFolder();
        // 2. 构建完整路径
        String folderPath = buildFolderPath(dateFolder, subFolder);
        // 3. 生成安全的文件名
        String totalFileName = generateSafeFilename(fileName);
        // 4. 构建完整Key (folder + filename)
        String key = folderPath + totalFileName;

        String uploadToken = generateUploadToken(key);

        // 上传文件
        Response response = uploadManager.put(fileBytes, key, uploadToken);
        log.info("---------->{}", response.bodyString());
        String resStr = response.bodyString();
        JSONObject resJson = JSONObject.parseObject(resStr);
        // 解析上传成功的结果
        DefaultPutRet putRet = null;
        // 返回文件访问路径
        return resJson.getString("key");
    }

    /**
     * 生成上传凭证
     */
    private String generateUploadToken(String key) {
        // 自定义上传策略
        StringMap policy = new StringMap()
                .put("mimeLimit", "image/jpeg;image/png;image/gif;application/pdf")
                .put("fsizeLimit", 10485760); // 10MB

        return auth.uploadToken(
                bucket,
                key,
                3600, // 凭证有效期(秒)
                policy
        );
    }

    /**
     * 生成安全的文件名 (UUID + 原始扩展名)
     */
    private String generateSafeFilename(String originalFilename) {
        String ext = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        return UUID.randomUUID().toString().replace("-", "") + ext;
    }

    public String generateDateFolder() {
        return DateUtil.formatDate(new Date());
    }

    /**
     * 构建完整文件夹路径
     */
    private String buildFolderPath(String dateFolder, String subFolder) {
        StringBuilder path = new StringBuilder();
        // 添加子文件夹（如果存在）
        if (StrUtil.isNotBlank(subFolder)) {
            // 规范化子文件夹路径
            String normalizedSubFolder = subFolder.trim();
            if (!normalizedSubFolder.endsWith("/")) {
                normalizedSubFolder += "/";
            }
            if (normalizedSubFolder.startsWith("/")) {
                normalizedSubFolder = normalizedSubFolder.substring(1);
            }
            path.append(normalizedSubFolder);
        }
        // 添加日期文件夹
        path.append(dateFolder).append("/");
        return path.toString();
    }


}